package com.bandi.tharshesnows.persistence;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class DBUtils {

	public void importDBFromAssets(Context context) {
		InputStream is = null;
		FileOutputStream fos = null;
		try {
			is = context.getAssets().open(Database.DB_NAME);
			File dbDir = new File(Environment.getDataDirectory(), "//data//"
					+ context.getPackageName() + "//databases//");
			if(!dbDir.exists()){
				dbDir.mkdirs();
			}
			File f = new File(Environment.getDataDirectory(), "//data//"
					+ context.getPackageName() + "//databases//"
					+ Database.DB_NAME);
			if (f.exists()) {
				f.delete();
			}
			f.createNewFile();
			fos = new FileOutputStream(f);
			byte[] buffer = new byte[2048];
			while (is.read(buffer) > -1) {
				fos.write(buffer);
			}
		} catch (Exception e) {
			Log.e("DB", "DB import failed.", e);
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				// ignore
			}
		}
	}

	public void exportToExternalStorage(Context context) {
		try {
			File sd = Environment.getExternalStorageDirectory();
			File data = Environment.getDataDirectory();

			if (sd.canWrite()) {
				String currentDBPath = "//data//" + context.getPackageName()
						+ "/" + "//databases//" + Database.DB_NAME;
				String backupDBPath = context.getPackageName() + "/"
						+ Database.DB_NAME;
				File currentDB = new File(data, currentDBPath);
				File backupDB = new File(sd, backupDBPath);

				if (currentDB.exists()) {
					FileChannel src = new FileInputStream(currentDB)
							.getChannel();
					FileChannel dst = new FileOutputStream(backupDB)
							.getChannel();
					dst.transferFrom(src, 0, src.size());
					src.close();
					dst.close();
				}
			}
		} catch (Exception e) {
			Log.e("DB", "DB export failed.", e);
		}
	}

}
